package sg.edu.nus.iss.vmcs.ui.listener;

import java.awt.event.ActionEvent;
import sg.edu.nus.iss.vmcs.controller.*;
import sg.edu.nus.iss.vmcs.entity.Coin;

import java.awt.event.ActionListener;

import sg.edu.nus.iss.vmcs.ui.CoinInputBox;
import sg.edu.nus.iss.vmcs.ui.CustomerPanel;
import sg.edu.nus.iss.vmcs.util.AccurateCoinValidatorAdapter;
import sg.edu.nus.iss.vmcs.util.BestCoinValidator;
import sg.edu.nus.iss.vmcs.util.CoinValidator;
import sg.edu.nus.iss.vmcs.util.CoinValidatorAdapter;
import sg.edu.nus.iss.vmcs.util.VMCSException;


public class CoinInputListener implements ActionListener {
	
	

	private CoinInputBox coinInputBox;
	
	private CoinReceiver coinReceiver;

	
	public CoinInputListener(CoinInputBox coinInputBox) {
		this.coinInputBox = coinInputBox;
		try {
			coinReceiver = new CoinReceiver(coinInputBox.getTxnController());
		} catch(VMCSException vmcse) {
			vmcse.printStackTrace();
		}
	}
	
	public void actionPerformed(ActionEvent arg0) {
			
		try{
			
			
			String coinId = arg0.getActionCommand();
			Coin coin = CustomerPanel.getCoins().get(coinId);
			//TODO will adapt a different implementation here ..
			//CoinValidator cv = new CoinValidatorAdapter(coin);
			//CoinValidator cv = new CoinValidatorAdapter(coin);
			//CoinValidator cv=new AccurateCoinValidatorAdapter(coin);
			CoinValidator cv = new CoinValidator(coin);
			
			
			if (cv.validateCoin()) {
				double coinsInserted = coin.getValue();				
				double previousCoinsInserted = coinInputBox.getMp().getTotalCoinsInserted();
				coinInputBox.getMp().setTotalCoinsInserted(previousCoinsInserted + coinsInserted);
				System.out.println("Total coin inserted: " + coinInputBox.getMp().getTotalCoinsInserted());
				coinReceiver.receiveCoin(coinInputBox.getMp().getTotalCoinsInserted());		
				coinInputBox.setInvalidLabel("");
								
			} else {
				coinInputBox.setInvalidLabel("Invalid Coin");
				coinReceiver.receiveCoin(coinInputBox.getMp().getTotalCoinsInserted());			
				coinReceiver.terminateFault();
				coinReceiver.refundCash();
				
				//TODO : Test Activate DrinkSelectionBox and Deactivate CoinInputBox
				coinReceiver.stopCoinReceiver();
				
				
				
				
			}
			
		//	coinInputBox.getMp().notifyObservers(coinInputBox.getMp().getTotalCoinsInserted() + " c");
			
		}catch(Exception e){
			e.printStackTrace();
		}
	}


	
}
